'''
Created on 2009-12-3

@author: wangyongtao
'''
import os
import logging
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.labs import taskqueue
import utility 
import cbnrss
import math
import spider
import datamodel

MAX_PER_PAGE = 20

class IndexPage(utility.BaseRequestHandler):
    def get(self):
        columns = datamodel.cbncolumn.get_all_columns()
        self.generate('index.html', {
                      'columns': columns,
                })

class SpiderPage(utility.BaseRequestHandler):
    def get(self):
        s = spider.crawler()
        s.crawler('http://www.1cbn.com/leadership/', False)
        self.response.out.write('spider finished')
        
class ColumnPage(utility.BaseRequestHandler):
    def get(self, columnID):
        if not columnID:
            self.error(403)
        colID = int(columnID)
        if colID <= 0:
            logging.error('specified column ID invalid: %d'%colID)
            self.error(403)
        column = datamodel.cbncolumn.get_column_cbnid(colID)
        if not column:
            logging.error('The specified Column ID has no corresponding column:%d'%colID)
            self.error(403)
            return
        action = self.request.get('action', None)
        if users.is_current_user_admin() and action.lower() == 'update':
            taskqueue.add(url='/task/column', params={'id': column.cbnid}, method='GET')
        page = self.pageHandler()
        count = column.get_count_show()
        offset = (page-1)*MAX_PER_PAGE
        shows = column.get_shows(MAX_PER_PAGE, offset) 
        pages = int(math.ceil(count/float(MAX_PER_PAGE)))
        prev = False
        if page > 1:
            prev = page -1
        next = False
        if page < pages:
            next = page + 1
        self.generate('column.html', {
                      'column': column,
                      'shows': shows,
                      'pages': range(1, pages+1),
                      'page': page,
                      'count': count,
                      'prev': prev,
                      'next': next,
                })

class TaskPage(webapp.RequestHandler):
    _ACTION_MAP = {
                   'default':   'columnAction',
                   'show':      'showAction',
                   'host':      'hostAction',
                   'column':    'columnAction',
                   'gallery':   'galleryAction',
                   }
    def get(self, target):
        logging.debug('Task target:%s'%target)
        actionName = TaskPage._ACTION_MAP['default']
        action = None
        if not target:
            action = getattr(self, actionName)
        else:
            target = target.lower()
            if target in TaskPage._ACTION_MAP:
                actionName = TaskPage._ACTION_MAP[target]
            action = getattr(self, actionName)
        logging.debug('task action:%s'%action)
        if action:
            action()
    
    def columnAction(self):
        columnID = self.request.get('id', None)
        if columnID:
            spider.update_column(columnID)
            
    def showAction(self):
        return False
    
    def hostAction(self):
        return False
            
    def galleryAction(self):
        return False
    
class MediaListPage(utility.BaseRequestHandler):
    def get(self):
        page = self.pageHandler()
        limit = self.limitHandler()
        offset = (page-1)*limit
        shows = datamodel.log.get_non_downloaded_shows(limit, offset)
        self.generate('media.xml', {'shows': shows,})
        
class UpdatePage(utility.BaseRequestHandler):
    def get(self):
        limit = 220
        key = self.request.get('key', None)
        result = self.request.get('result', 0)
        result = int(result)
        logging.debug('update download status key:%s'%key)
        logging.debug('update download status result:%d'%result)
        successed = True
        if result == 0:
            successed = False
        if key:
            datamodel.log.update_show_download(key, successed)
            self.response.out.write('update video download finished')
        else:
            action = self.request.get('action',None)
            if action =='init':
                self.response.out.write('init show')
                shows = datamodel.log.get_non_def_shows(limit)
                for show in shows:
                    show.downloaded = False
                    show.put()
class ShowListPage(utility.BaseRequestHandler):
    COLUMN_ID_BRAINSTORM = 19
    COLUMN_ID_BOSSTOWN = 38
    def get(self):
        page = self.pageHandler()
        limit = self.limitHandler()
        colid = self.request.get('col', None)
        logging.info('col id:%s'%colid)
        if not colid:
            colid = ShowListPage.COLUMN_ID_BOSSTOWN
       
        offset = (page-1)*limit
        shows = datamodel.log.get_non_downloaded_shows_by_colid(limit, offset, colid)
        self.generate('media.xml', {'shows': shows,})
        
class FetchSodexoHandler(utility.BaseRequestHandler):
    def get(self):
        url = self.request.get('url', None)
        if not url:
            url = 'http://www.club.cn.sodexo.com/'
        spider.fetch_sodexo_page(url) 

class FetchSodexoUnitHandler(utility.BaseRequestHandler):
    def get(self):
        uid = self.request.get('uid', None)
        if not uid:
            uid = 5069
        spider.fetch_business_unit(uid)
        
class DownloadedPage(utility.BaseRequestHandler):
    def get(self):
        page = self.pageHandler()
        count_total = datamodel.cbnshow.get_show_count()
        count_downloaded = datamodel.cbnshow.get_downloaded_show_count()
        offset = (page-1)*MAX_PER_PAGE
        shows = datamodel.cbnshow.get_downloaded_shows(MAX_PER_PAGE, offset)
        pages = int(count_downloaded/MAX_PER_PAGE)+1
        prev = False
        if page > 1:
            prev = page -1
        next = False
        if page < pages:
            next = page + 1
        self.generate('downloaded.html', {
                      'shows': shows,
                      'pages': range(1, pages+1),
                      'page': page,
                      'count_total': count_total,
                      'count_downloaded':count_downloaded,
                      'prev': prev,
                      'next': next,
                })
        
                
        
mainApplication = webapp.WSGIApplication([
            ('/spider.*', SpiderPage),
            ('/fetchsodexo.*', FetchSodexoHandler),
            ('/fetchunit.*', FetchSodexoUnitHandler),
            ('/showdownload.*', MediaListPage),
            ('/colshowlist.*', ShowListPage),
            ('/update.*', UpdatePage),
            ('/downloaded.*', DownloadedPage),
            (r'/task/(.*)', TaskPage),
            (r'/column/(.*)', ColumnPage),
            ('/.*', IndexPage)], debug=utility.DEBUG)

rssApplication = webapp.WSGIApplication([
            ('/.*', cbnrss.IndexPage)], debug= utility.DEBUG)

applications = {
  'cbnchannel.appspot.com': mainApplication,
  'localhost':mainApplication,
  'rss.cbnchannel.appspot.com': rssApplication,
}
       
def main():
    run_wsgi_app(applications[os.environ['SERVER_NAME']])

if __name__ == "__main__":
    main()        